<template>
  <div class="app-container">
    <el-card shadow="hover" class="data-table">
      <el-table
        v-loading="loading"
        :data="Lists"
        row-key="id"
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        class="data-table__content"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="id" label="序号" width="150" />
        <!-- <el-table-column prop="name" label="配置标识"  /> -->
        <el-table-column prop="title" label="标题" />

        <!-- <el-table-column prop="img_url" label="图片" >
          <template #default="{ row }">
            <el-image
              style="width: 50px; height: 50px; border-radius: 50%"
              :src="row.img_url || 'https://xcx.yumeishangmao.com/uploads/8b112625e64da7e7dc69fab1044487e5.png'"
              :preview-src-list="[row.img_url]"
            />
          </template>
        </el-table-column> -->
        <el-table-column prop="sort" label="排序" width="150" />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.type == 1" type="success">文本</el-tag>
            <el-tag v-else-if="scope.row.type == 2" type="success">编辑器</el-tag>
            <el-tag v-else-if="scope.row.type == 3" type="success">开关</el-tag>
            <el-tag v-else-if="scope.row.type == 4" type="success">未知</el-tag>

            <el-tag v-else type="info"></el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="value" label="内容" width="200">
          <template #default="scope">
            <span v-if="scope.row.type == 3">
              <!-- {{ scope.row.value == 1 ? '开启' : '关闭' }} -->
              <div style="display: flex">
                <el-switch
                  v-model="scope.row.value"
                  :active-value="'1'"
                  :inactive-value="'0'"
                  @change="handleStatusChange2(scope.row)"
                ></el-switch>
              </div>
            </span>
            <span v-else>{{ scope.row.value }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" fixed="right" align="left" width="200">
          <template #default="scope">
            <el-button
              type="primary"
              link
              size="small"
              icon="edit"
              @click.stop="handleOpenDialog(scope.row.id, scope.row)"
            >
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="600px"
      @closed="handleCloseDialog"
    >
      <el-form ref="FormRef" :model="formData" :rules="rules" label-width="120px">
        <!-- <el-form-item label="配置标识" prop="name">
          <el-input v-model="formData.name" placeholder="请输入配置标识" />
        </el-form-item> -->

        <el-form-item label="标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入标题" />
        </el-form-item>

        <el-form-item label="图片">
          <SingleImageUpload v-model="formData.imgUrl" />
        </el-form-item>

        <el-form-item label="显示排序" prop="sort">
          <el-input-number
            v-model="formData.sort"
            controls-position="right"
            style="width: 100px"
            :min="0"
          />
        </el-form-item>

        <!-- <el-form-item label="类型" >
          <el-radio-group v-model="formData.type">
            <el-radio :value="1">文本</el-radio>
            <el-radio :value="2">编辑器</el-radio>
            <el-radio :value="3">开关</el-radio>
            <el-radio :value="4">未知</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item> -->

        <el-form-item :label="formData.type == 3 ? '开关' : '内容'" prop="value">
          <el-switch
            v-if="formData.type == 3"
            v-model="formData.value"
            :active-value="'1'"
            :inactive-value="'0'"
            @change="handleStatusChange(formData)"
          ></el-switch>

          <el-input v-if="formData.type != 3" v-model="formData.value" placeholder="请输入内容" />
        </el-form-item>

        <WangEditor
          v-model="formData.content"
          height="200px"
          style="width: 80%; margin-left: 10%"
        />
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "分类",
  inheritAttrs: false,
});

import StateAPI, { StateVO, StateForm } from "@/api/system/state.api";

// const queryFormRef = ref();
const FormRef = ref();

const loading = ref(false);
const selectIds = ref<number[]>([]);
const queryParams = reactive<any>({});

const dialog = reactive({
  title: "",
  visible: false,
});

const Lists = ref<StateVO[]>();
const formData = reactive<StateForm>({
  id: "0",
  name: "",
  title: "",
  imgUrl: "",
  sort: 1,
  type: 1,
  value: "",
  content: "",
});

const rules = reactive({
  title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
  sort: [{ required: true, message: "显示排序不能为空", trigger: "blur" }],
});

// 查询
function handleQuery() {
  console.log(queryParams);
  loading.value = true;

  StateAPI.getList(queryParams)
    .then((res) => {
      Lists.value = res;
    })
    .catch((error) => {
      console.error("查询失败:", error);
    })
    .finally(() => {
      loading.value = false;
    });

  loading.value = false;
}

// 重置查询
// function handleResetQuery() {
//   queryFormRef.value.resetFields();
//   handleQuery();
// }

// 处理选中项变化
function handleSelectionChange(selection: any) {
  selectIds.value = selection.map((item: any) => item.id);
}

/**
 * 打开新增弹窗
 *
 * @param Id ID
 */
async function handleOpenDialog(Id?: string, data?: StateVO) {
  if (Id) {
    dialog.title = "修改";

    let content2 = data?.content || "";
    content2 = content2.replace(/<[^>]+>/g, ""); // 移除所有HTML标签
    content2 = content2.replace(/&nbsp;/g, ""); // 移除所有空
    content2 = content2.replace(/&lt;/g, "<"); // 替换&lt;为<
    content2 = content2.replace(/&gt;/g, ">"); // 替换&gt;为>
    content2 = content2.replace(/&quot;/g, '"'); // 替换

    console.log("content2", content2);
    formData.value = data?.value || "";
    formData.content = escape2Html(content2);
    Object.assign(formData, data);
  } else {
    dialog.title = "新增";
  }

  dialog.visible = true;
}

const escape2Html = (str: any) => {
  const arrEntities: { [key: string]: string } = {
    lt: "<",
    gt: ">",
    nbsp: " ",
    amp: "&",
    quot: '"',
  };
  return str.replace(/&(lt|gt|nbsp|amp|quot);/gi, function (all: string, t: string) {
    return arrEntities[t];
  });
};

let isInit = true;

function handleStatusChange(row: any) {
  if (isInit) {
    isInit = false;
    return;
  }
  const formJson = {
    dataId: row.id, //ID
    configTitle: row.title, //标题
    value: row.value, //非编辑器的值(注册邀请码开关值为0或1)
    content: "", //编辑器内容
    sort: row.sort, //排序
  };
  StateAPI.update(formJson)
    .then(() => {
      //ElMessage.success("修改成功");
      handleQuery();
    })
    .catch((error) => {
      console.error("状态更新失败:", error);
      //ElMessage.error("修改失败");
    });
}

function handleStatusChange2(row: any) {
  const formJson = {
    dataId: row.id, //ID
    configTitle: row.title, //标题
    value: row.value, //非编辑器的值(注册邀请码开关值为0或1)
    content: "", //编辑器内容
    sort: row.sort, //排序
  };
  StateAPI.update(formJson)
    .then(() => {
      //ElMessage.success("修改成功");
      handleQuery();
    })
    .catch((error) => {
      console.error("状态更新失败:", error);
      //ElMessage.error("修改失败");
    });
}

// 提交表单
function handleSubmit() {
  FormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const formJson = ref();
      if (formData.content) {
        formJson.value = {
          dataId: formData.id, //ID
          imgUrl: formData.imgUrl, // 图片
          configTitle: formData.title, //标题
          value: formData.value, //非编辑器的值(注册邀请码开关值为0或1)
          content: escape2Html(formData.content), //编辑器内容
          sort: formData.sort, //排序
        };
      } else {
        formJson.value = {
          dataId: formData.id, //ID
          imgUrl: formData.imgUrl, // 图片
          configTitle: formData.title, //标题
          value: formData.value, //非编辑器的值(注册邀请码开关值为0或1)
          content: "", //编辑器内容
          sort: formData.sort, //排序
        };
      }

      StateAPI.update(formJson.value)
        .then(() => {
          ElMessage.success("修改成功");
          handleCloseDialog();
          handleQuery();
        })
        .finally(() => (loading.value = false));

      loading.value = false;
    }
  });
}

// 重置表单
function resetForm() {
  FormRef.value.resetFields();
  FormRef.value.clearValidate();

  formData.id = undefined;
  formData.sort = 1;
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  resetForm();
}

onMounted(() => {
  handleQuery();
});
</script>
